import { buffer } from '@kit.ArkTS';
import   STATUS_CODES  from '../../http'



const TYPE = 'content-type';
const OSTREAM = 'application/octet-stream';

 export default function (res, code=200, data='', headers={}) {
  let k, obj={};
  for (k in headers) {
    obj[k.toLowerCase()] = headers[k];
  }

  let type = obj[TYPE] || res.getHeader(TYPE);

  if (!!data && typeof data.pipe === 'function') {
    obj[TYPE] = type || OSTREAM;
    for (k in obj) {
      res.setHeader(k, obj[k]);
    }
    return data.pipe(res);
  }

  if (data instanceof buffer.Buffer/*Buffer*/) {
    type = type || OSTREAM; // prefer given
  } else if (typeof data === 'object') {
    data = JSON.stringify(data);
    type = type || 'application/json;charset=utf-8';
  } else {
    data = data || STATUS_CODES[code];
  }

  obj[TYPE] = type || 'text/plain';
  obj['content-length'] = buffer.byteLength(data);

  res.writeHead(code, obj);
  res.end(data);
}

